package 二叉树的层序遍历;

import java.util.*;

/**
 * @author: zhengtao
 * @description: 在每个树行中找最大值
 *
 * @version: 1.0
 * @date: 2022/10/29  14:49
 */
public class Demo515 {
    public List<Integer> largestValues(TreeNode root) {
        List<Integer> res=new ArrayList<>();
        if(root==null){
            return res;
        }
        Queue<TreeNode> queue=new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()){
            int size = queue.size();
            ArrayList<Integer> temp=new ArrayList();
            while (size-->0){
                TreeNode poll = queue.poll();
                temp.add(poll.val);
                if(poll.left!=null){
                    queue.add(poll.left);
                }
                if(poll.right!=null){
                    queue.add(poll.right);
                }
            }
            res.add(Collections.max(temp));
        }
        return res;
    }
    /**
     * Definition for a binary tree node.
     * */
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
